<template>
  <div class="login-wrap center">
    <div class="login-inner center">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >登陆</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      // this.$refs.xxx 是拿到节点的意思 相当于是之前document.getElementById
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //   alert("submit!");
          //校验成功走这里 校验成功就登陆
          this.$axios.post("login", this.ruleForm).then((res) => {
            console.log(res.data.meta.msg);
            if (res.data.meta.msg == "登录成功") {
              console.log(111);
              localStorage.setItem("token", res.data.data.token);
              this.$router.push("/users");
            }
            //判断登陆成功 存token 身份信息
            //登陆成功跳转到users页面
          });
          //登陆成功会返回 电话 邮箱 用户名 更重要是有一个身份证token
        } else {
          console.log("error submit!!");
          //校验不成功走这里

          return false;
        }
      });
    },
  },
  created() {},
  mounted() {},
  components: {},
  computed: {},
  watch: {},
  beforeRouteEnter(to, from, next) {
    if (localStorage.getItem("token")) {
      next("/users");
    } else {
      next();
    }
  },
  //守卫登陆页面 如果已经登陆了 就不能访问登陆页面了 而是跳转到users
  // 如果没有登陆就能正常访问这个页面
};
</script>

<style lang="scss" scoped>
.login-wrap {
  background: #314b68;
  width: 100vw;
  height: 100vh;

  .login-inner {
    width: 500px;
    height: 300px;
    background: #fff;
  }
  .el-form {
    width: 80%;
  }
}
</style>
